#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QImage>
#include <QLabel>
#include <QPixmap>

void MainWindow::ShowImage(unsigned char *img_buff, int w, int h)
{
    uint rgbValue;
    unsigned char *curPixel = NULL;

    //创建图像
    QImage qiImage(w, h, QImage::Format_Indexed8);
    qiImage.setColorCount(256);
    for (int nColorCnt = 0; nColorCnt < 256; nColorCnt++)
    {
        rgbValue = (nColorCnt << 16) + (nColorCnt << 8) + nColorCnt;
        rgbValue = rgbValue | 0xFF000000;
        qiImage.setColor(nColorCnt, rgbValue);
    }
    curPixel = img_buff;
    for (int wByteCnt = 0; wByteCnt < h; wByteCnt++)
    {
        for (int nBitCnt = 0; nBitCnt < w; nBitCnt++)
        {
            rgbValue = *curPixel;
            qiImage.setPixel(nBitCnt, wByteCnt, rgbValue);
            curPixel++;
        }
    }

    //绘制图像
    QImage qiImagetemp = qiImage.scaled(w, h, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    QPixmap qpImagePixmap = QPixmap::fromImage(qiImagetemp);

    //1.直接原样显示
    // ui->label->setPixmap(qpImagePixmap);

    //2.自适应lable显示
    int with = ui->label->width();
    int height = ui->label->height();
    // QPixmap fitpixmap = qpImagePixmap.scaled(with, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);  // 饱满填充
    QPixmap fitpixmap = qpImagePixmap.scaled(with, height, Qt::KeepAspectRatio, Qt::SmoothTransformation);  // 按比例缩放
    ui->label->setPixmap(fitpixmap);
}


void MainWindow::on_pushButtonTestShowImg_clicked()
{
    unsigned char img_buff[32 * 24];
    memset(img_buff, 0x55, 32 * 24);
    ShowImage(img_buff, 32, 24);
}
